package chinesechess.view;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import chinesechess.DTO.DBConnection;
import chinesechess.util.MD5Util;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.sql.*;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JButton changePasswordButton;
    
    public LoginFrame() {
        setTitle("中国象棋-登录界面");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // 创建通知栏
        JLabel notificationLabel = new JLabel("tips：增加了回车键登录和config按钮的Cursor效果");
        notificationLabel.setHorizontalAlignment(JLabel.CENTER);
        notificationLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        notificationLabel.setForeground(new Color(60, 60, 60));
        notificationLabel.setBackground(new Color(255, 247, 230));
        notificationLabel.setOpaque(true);
        notificationLabel.setBorder(BorderFactory.createEmptyBorder(8, 0, 8, 0));
        
        // 主面板使用边框布局
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 设置标签和输入框
        JLabel userLabel = new JLabel("用户名:");
        JLabel passLabel = new JLabel("密码:");
        usernameField = new JTextField(15);
        passwordField = new JPasswordField(15);
        
        // 添加组件到输入面板
        gbc.gridx = 0; gbc.gridy = 0;
        inputPanel.add(userLabel, gbc);
        gbc.gridx = 1;
        inputPanel.add(usernameField, gbc);
        
        gbc.gridx = 0; gbc.gridy = 1;
        inputPanel.add(passLabel, gbc);
        gbc.gridx = 1;
        inputPanel.add(passwordField, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        loginButton = createStyledButton("登录", new Color(60, 141, 188));
        registerButton = createStyledButton("注册", new Color(0, 166, 90));
        changePasswordButton = createStyledButton("修改密码", new Color(243, 156, 18));
                
        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);
        buttonPanel.add(changePasswordButton);
        
        // 添加事件监听
        setupEventListeners();
        
        // 将通知栏添加到主面板的顶部
        mainPanel.add(notificationLabel, BorderLayout.NORTH);
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
        
        initDatabase();
    }
    
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setPreferredSize(new Dimension(100, 35)); // 设置按钮大小
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14)); // 加大字体
        button.setCursor(new Cursor(Cursor.HAND_CURSOR)); // 添加手型光标
        
        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor.brighter());
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });
        
        return button;
    }
    
    private void setupEventListeners() {
        loginButton.addActionListener(e -> login());
        registerButton.addActionListener(e -> showRegisterDialog());
        changePasswordButton.addActionListener(e -> showChangePasswordDialog());
        
        // 添加回车键登录
        KeyAdapter enterKeyListener = new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    login();
                }
            }
        };
        
        usernameField.addKeyListener(enterKeyListener);
        passwordField.addKeyListener(enterKeyListener);
    }
    
    private void login() {
        String username = usernameField.getText();
        String password = MD5Util.encrypt(new String(passwordField.getPassword()));
        
        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空！");
            return;
        }
        
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT * FROM users WHERE name = ? AND password = ?")) {
            
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                // 登录成功
                String nickname = rs.getString("nickname");
                int userId = rs.getInt("id");
                JOptionPane.showMessageDialog(this, "登录成功！欢迎游玩，" + nickname);
                this.dispose();
                new ChessBoard(userId, nickname);
            } else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误！");
            }
            
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "登录失败：" + ex.getMessage());
        }
    }
    
    private void initDatabase() {
        try {
            System.out.println("初始化数据库...");
            DBConnection.createUserTable();
            DBConnection.createScoreTable();
            DBConnection.createBattleRecordTable();
        } catch (Exception e) {
            System.err.println("数据库初始化失败: " + e.getMessage());
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, 
                "数据库初始化失败：" + e.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void showRegisterDialog() {
        JDialog dialog = new JDialog(this, "注册新用户", true);
        dialog.setSize(300, 250);
        dialog.setLocationRelativeTo(this);
        
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        
        // 用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("用户名:"), gbc);
        
        gbc.gridx = 1;
        JTextField regUsernameField = new JTextField(15);
        panel.add(regUsernameField, gbc);
        
        // 密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("密码:"), gbc);
        
        gbc.gridx = 1;
        JPasswordField regPasswordField = new JPasswordField(15);
        panel.add(regPasswordField, gbc);
        
        // 昵称
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("游戏昵称:"), gbc);
        
        gbc.gridx = 1;
        JTextField nicknameField = new JTextField(15);
        panel.add(nicknameField, gbc);
        
        // 注册按钮
        JButton submitButton = createStyledButton("提交注册", new Color(129, 212, 250));
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(submitButton, gbc);
        
        submitButton.addActionListener(e -> {
            String username = regUsernameField.getText();
            String password = MD5Util.encrypt(new String(regPasswordField.getPassword()));
            String nickname = nicknameField.getText();
            
            if (username.isEmpty() || password.isEmpty() || nickname.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "所有字段都必须填写！");
                return;
            }
            
            try (Connection conn = DBConnection.getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(
                         "INSERT INTO users (name, password, nickname) VALUES (?, ?, ?)",
                         Statement.RETURN_GENERATED_KEYS)) {
                
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                pstmt.setString(3, nickname);
                
                pstmt.executeUpdate();
                
                // 获取新插入用户的ID
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    int userId = rs.getInt(1);
                    // 初始化用户积分
                    DBConnection.initUserScore(userId, nickname);
                }
                
                JOptionPane.showMessageDialog(dialog, "注册成功！");
                dialog.dispose();
                
            } catch (SQLException ex) {
                if (ex.getErrorCode() == 1062) { // MySQL重复键错误码
                    JOptionPane.showMessageDialog(dialog, "该用户名已被注册！");
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(dialog, "注册失败：" + ex.getMessage());
                }
            }
        });
        
        dialog.add(panel);
        dialog.setVisible(true);
    }
    
    private void showChangePasswordDialog() {
        JDialog dialog = new JDialog(this, "修改密码", true);
        dialog.setSize(300, 250);
        dialog.setLocationRelativeTo(this);
        
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        
        // 用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("用户名:"), gbc);
        
        gbc.gridx = 1;
        JTextField usernameField = new JTextField(15);
        panel.add(usernameField, gbc);
        
        // 原密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("原密码:"), gbc);
        
        gbc.gridx = 1;
        JPasswordField oldPasswordField = new JPasswordField(15);
        panel.add(oldPasswordField, gbc);
        
        // 新密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("新密码:"), gbc);
        
        gbc.gridx = 1;
        JPasswordField newPasswordField = new JPasswordField(15);
        panel.add(newPasswordField, gbc);
        
        // 确认新密码
        gbc.gridx = 0;
        gbc.gridy = 3;
        panel.add(new JLabel("确认新密码:"), gbc);
        
        gbc.gridx = 1;
        JPasswordField confirmPasswordField = new JPasswordField(15);
        panel.add(confirmPasswordField, gbc);
        
        // 提交按钮
        JButton submitButton = createStyledButton("确认修改", new Color(243, 156, 18));
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        panel.add(submitButton, gbc);
        
        submitButton.addActionListener(e -> {
            String username = usernameField.getText();
            String oldPassword = MD5Util.encrypt(new String(oldPasswordField.getPassword()));
            String newPassword = new String(newPasswordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            
            // 验证输入
            if (username.isEmpty() || oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "所有字段都必须填写！");
                return;
            }
            
            if (!newPassword.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(dialog, "两次输入的新密码不一致！");
                return;
            }
            
            try (Connection conn = DBConnection.getConnection();
                 PreparedStatement checkStmt = conn.prepareStatement(
                         "SELECT * FROM users WHERE name = ? AND password = ?")) {
                
                // 验证原密码
                checkStmt.setString(1, username);
                checkStmt.setString(2, oldPassword);
                
                ResultSet rs = checkStmt.executeQuery();
                if (!rs.next()) {
                    JOptionPane.showMessageDialog(dialog, "用户名或原密码错误！");
                    return;
                }
                
                // 更新密码
                try (PreparedStatement updateStmt = conn.prepareStatement(
                        "UPDATE users SET password = ? WHERE name = ?")) {
                    
                    updateStmt.setString(1, MD5Util.encrypt(newPassword));
                    updateStmt.setString(2, username);
                    updateStmt.executeUpdate();
                    
                    JOptionPane.showMessageDialog(dialog, "密码修改成功！");
                    dialog.dispose();
                }
                
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(dialog, "修改密码失败：" + ex.getMessage());
            }
        });
        
        dialog.add(panel);
        dialog.setVisible(true);
    }
} 